import forgotPasswordPhoneApi from '@/api/user/forgotPasswordPhoneApi'
import { getAppNav } from '@/App'
import CEmailOrPhoneCode from '@/components/user/CEmailOrPhoneCode'
import IForgotPasswordByPhoneForm from '@/model/form/user/IForgotPasswordByPhoneForm'
import ILoginByPhoneForm from '@/model/form/user/ILoginByPhoneForm'
import { useAppSelector } from '@/store'
import { ToastError, ToastSuccess } from '@/util/CommonUtil'
import { RSAEncryptPro, passwordRSAEncrypt } from '@/util/UserUtil'
import Validator from '@/util/Validator'
import { Form, Button } from '@douyinfe/semi-ui'
import { ReactFieldError } from '@douyinfe/semi-ui/lib/es/form'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'

interface IForgotPasswordSendByPhone {
  loading: boolean
  setLoading: Dispatch<SetStateAction<boolean>>
  noPassword: boolean
}

export default function ForgotPasswordSendByPhone(
  props: IForgotPasswordSendByPhone
) {
  const [codeText, setCodeText] = useState('获取验证码')
  const timer = useRef<NodeJS.Timer>()
  const rsaPublicKey = useAppSelector((state) => state.common.rsaPublicKey)

  useEffect(() => {
    return () => {
      clearTimer()
    }
  }, [timer])

  function clearTimer() {
    if (timer.current) {
      clearInterval(timer.current)
    }
  }

  return (
    <Form
      disabled={props.loading}
      className="w-300 m-t-10"
      onSubmit={(form) => {
        if (props.loading) return
        submitClick(
          form as IForgotPasswordByPhoneForm,
          props.setLoading,
          rsaPublicKey
        )
      }}
      onSubmitFail={(errors: Record<string, ReactFieldError>) => {
        errors.code ? ToastError(errors.code as string) : null
      }}
    >
      <Form.Input
        field="phone"
        placeholder="手机号"
        noLabel
        rules={[{ required: true, message: '请输入手机号' }]}
        showClear
        validate={Validator['phoneValidate']}
      />
      <Form.Input
        field="newPassword"
        placeholder="新密码"
        noLabel
        validate={Validator['passwordValidate']}
        showClear
        mode="password"
      />
      <CEmailOrPhoneCode
        noLabel
        setCodeText={setCodeText}
        timer={timer}
        clearTimer={clearTimer}
        codeText={codeText}
        loading={props.loading}
        sendCodeType={5}
      ></CEmailOrPhoneCode>
      <Button
        block
        theme="solid"
        type="warning"
        size="large"
        loading={props.loading}
        htmlType="submit"
        className="m-t-10"
      >
        {props.noPassword ? '设置密码' : '重置密码'}
      </Button>
      <Button
        disabled={props.loading}
        block
        className="m-t-10"
        onClick={() => {
          if (props.noPassword) {
            getAppNav()(-1)
          } else {
            getAppNav()('/login')
          }
        }}
      >
        {props.noPassword ? '返回' : '去登录'}
      </Button>
    </Form>
  )
}

// 点击提交按钮
function submitClick(
  form: IForgotPasswordByPhoneForm,
  setLoading: Dispatch<SetStateAction<boolean>>,
  rsaPublicKey: string
) {
  setLoading(true) // 设置 loading状态

  const date = new Date()
  form.newOrigPassword = RSAEncryptPro(form.newPassword, rsaPublicKey, date)
  form.newPassword = passwordRSAEncrypt(form.newPassword, rsaPublicKey, date)

  forgotPasswordPhoneApi(form)
    .then(({ data }) => {
      ToastSuccess(data.msg)
      setLoading(false)
      getAppNav()('/login')
    })
    .catch(() => {
      setLoading(false)
    })
}
